package com.longrise.co.ui.carlife.webview;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.longrise.co.R;
import com.longrise.co.ui.carlife.contract.CarLifeContract;
import com.longrise.co.ui.carlife.model.CarLifeModel;
import com.longrise.co.ui.carlife.model.TakePhotoBean;
import com.longrise.co.ui.carlife.presenter.CarLifePresenter;
import com.longrise.co.ui.kckp.HeNanSurfaceViewCameraActivity;
import com.longrise.co.utils.StringUtils;
import com.ly.common.base.BaseActivity;
import com.ly.common.baseapp.AppManager;
import com.ly.common.commonwidget.LoadingDialog;
import com.ly.common.dialog.DialogOnClickListener;
import com.ly.common.dialog.MDAlertDialog;

import org.json.JSONObject;

import butterknife.Bind;
import longrise.phone.com.baidulib.baidu.LocationHelper;

/**
 * Created by luoyang on 2016/6/6.
 */
public class WebViewActivity extends BaseActivity<CarLifePresenter, CarLifeModel> implements CarLifeContract.View<String>,DialogOnClickListener {
    //标题
    private String title;
    //链接
    private String url;

    @Bind(R.id.wb_content)
    WebView mWebView;

    private String mCurrentType;

    private MDAlertDialog mDialog;

    public static final int SETTING_LOCATION_WEBVIEW = 889;

    private LocationHelper locationHelper;

    private Dialog mLoadingDialog;

    public static void gotoWebActivity(Context context, String title, String url) {
        Intent intent = new Intent(context, WebViewActivity.class);
        intent.putExtra("title", title);
        intent.putExtra("url", url);
        context.startActivity(intent);
    }

    private void initDialog() {
        mDialog = new MDAlertDialog.Builder(this)
                .setContentText("GPS定位功能未开启,是否打开？")
                .setOnclickListener(this)
                .build();
    }

    @Override
    protected void doBeforeSetcontentView() {
        //设置昼夜主题
        initTheme();
        // 把actvity放到application栈中管理
        AppManager.getAppManager().addActivity(this);
        // 无标题
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 设置竖屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_webview;
    }

    @Override
    public void initPresenter() {
        mPresenter.setVM(this , mModel);
    }

    @Override
    public void initView() {
        Intent intent = getIntent();
        title = intent.getStringExtra("title");
        url = intent.getStringExtra("url");

        mWebView.clearHistory();
        //扩大比例的缩放
        mWebView.getSettings().setUseWideViewPort(true);
        //设置编码　　
        mWebView.getSettings().setDefaultTextEncodingName("utf-8");
        //支持javascript
        mWebView.getSettings().setJavaScriptEnabled(true);
        // 设置可以支持缩放
        mWebView.getSettings().setSupportZoom(false);
        // 设置出现缩放工具
        mWebView.getSettings().setBuiltInZoomControls(false);

        //设置 缓存模式 不用缓存 使用localStorage
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.getSettings().setAppCacheMaxSize(1024 * 1024 * 8);
        String absolutePath = mContext.getApplicationContext().getCacheDir().getAbsolutePath();
        mWebView.getSettings().setAppCachePath(absolutePath);
        mWebView.getSettings().setAllowFileAccess(true);
        mWebView.getSettings().setAppCacheEnabled(true);

        //自适应屏幕
        mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        mWebView.getSettings().setLoadWithOverviewMode(true);


        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(final WebView view, final String url) {
                //返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
                if(url == null || "".equals(url)) return false;

                if(url.startsWith("http") || url.startsWith("https")) {
                    //http和https协议开头的执行正常的流程
                    view.loadUrl(url);
                    return true;
                } else {
                    //其他的URL则会开启一个Acitity然后去调用原生APP
                    Intent in = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    if (in.resolveActivity(getPackageManager()) == null) {
                        //系统中不存在这个activity
                        view.post(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(WebViewActivity.this, "应用未安装", Toast.LENGTH_SHORT).show();
                                view.loadUrl(url);
                            }
                        });

                    } else {
                        in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
                        startActivity(in);
                    }
                    return true;

                }
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                showLoadingDialog();
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if(mLoadingDialog != null) {
                    mLoadingDialog.cancel();
                }
            }
        });

        mWebView.addJavascriptInterface(new JsCallImpl(), "JSObject");

        mWebView.loadUrl(url);
    }

    private void showLoadingDialog() {
        if(mLoadingDialog == null) {
            mLoadingDialog = LoadingDialog.showDialogForLoading(this,"正在加载中...",true);
        }
        mLoadingDialog.show();
    }


    @Override
    public void requestSuccess(final String s) {
        //上传成功
//        mWebView.loadUrl("javascript:kckphnphoto('"+ 45 + "')");
        mWebView.post(new Runnable() {
            @Override
            public void run() {
                mWebView.loadUrl("javascript:kckphnphoto('"+ s + "')");
            }
        });
    }

    @Override
    public void onComplete() {

    }

    @Override
    public void clickLeftButton(View view) {
        //
        if(mDialog != null) {
            mDialog.dismiss();
        }
        showErrorTip("定位失败，请开启位置信息开关。");
        //定位成功
        mWebView.post(new Runnable() {
            @Override
            public void run() {
                mWebView.loadUrl("javascript:kckphnlocation('-1')");
            }
        });
    }

    @Override
    public void clickRightButton(View view) {
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        startActivityForResult(intent, SETTING_LOCATION_WEBVIEW);
        if(mDialog != null) {
            mDialog.dismiss();
        }
    }

    interface JsCall {

        /**
         * 拍照
         * @param type 照片类型
         */
        @JavascriptInterface
        void photoGraph(String type);

        /**
         * 定位
         * @param data
         */
        @JavascriptInterface
        void location(String data);

        /**
         * 关闭快处快赔
         */
        @JavascriptInterface
        void finishKcKp();

        @JavascriptInterface
        void alert(String data);


    }

     class JsCallImpl implements JsCall, LocationHelper.LocationListener {


         @JavascriptInterface
         @Override
         public void location(String data) {
             //开始定位
             if(locationHelper == null) {
                 locationHelper  = new LocationHelper(WebViewActivity.this, this);
             }
             locationHelper.start();
         }


        @JavascriptInterface
        @Override
        public void photoGraph(String type) {
            mCurrentType = type;
            TakePhotoBean bean = getPhotoBeanByType(type);
            if(bean == null) {
                return ;

            }
            Intent intent = new Intent();
            Bundle bundle = new Bundle();
            if(bean.backGroundResourceId != 0) {
                bundle.putInt("backGroundResourceId", bean.backGroundResourceId);
            }

            if(!com.ly.common.commonutils.StringUtils.isEmpty(bean.title)) {
                bundle.putString("title", bean.title);
            }
            intent.putExtras(bundle);
            intent.setClass(mContext, HeNanSurfaceViewCameraActivity.class);
            startActivityForResult(intent, 99);
        }


         @JavascriptInterface
         @Override
         public void finishKcKp() {
            WebViewActivity.this.finish();
         }

         @JavascriptInterface
         @Override
         public void alert(String data) {
             if(!com.ly.common.commonutils.StringUtils.isEmpty(data)) {
                 showLongToast(data);
             }
         }

         private TakePhotoBean getPhotoBeanByType(String type) {
             TakePhotoBean bean = null;
            try {
                bean = new TakePhotoBean();
                switch (Integer.parseInt(type)) {
                    case 0 :
                        bean.title = "车头前方照片";
                        bean.backGroundResourceId = R.drawable.car_6;
                        break;
                    case 1 :
                        bean.title = "车尾后方照片";
                        bean.backGroundResourceId = R.drawable.car_7;
                        break;
                    case 2 :
                        bean.title = "擦碰点照片";
                        bean.backGroundResourceId = R.drawable.car_5;
                        break;
                    case 3 :
                        bean.title = "事故侧方照片";
                        bean.backGroundResourceId = R.drawable.car_8;
                        break;
                    case 4 :
                        bean.title = "对方驾驶证照片";
                        bean.backGroundResourceId = R.drawable.jsz_4;
                        break;
                    case 5 :
                        bean.title = "对方行驶证照片";
                        bean.backGroundResourceId = R.drawable.xsz_5;
                        break;
                    case 6 :
                        bean.title = "银行卡正面照片";
                        bean.backGroundResourceId = R.drawable.card_6;
                        break;
                    case 7 :
                        bean.title = "身份证正面照片";
                        bean.backGroundResourceId = R.drawable.sfz_7;
                        break;
                    case 8 :
                        bean.title = "身份证反面照片";
                        bean.backGroundResourceId = R.drawable.sfz_8;
                        break;
                    case 9 :
                     /*   bean.title = "对方签名";
                        bean.backGroundResourceId = R.drawable.car_6;*/
                        break;
                    case 10 :
                      /*  bean.title = "已方签名";
                        bean.backGroundResourceId = R.drawable.car_6;*/
                        break;
                    case 11 :
                        bean.title = "对方受损部位";
                        bean.backGroundResourceId = R.drawable.car_6;
                        break;
                    case 12 :
                        bean.title = "已方受损部位";
                        bean.backGroundResourceId = R.drawable.car_6;
                        break;
                    case 13 :
                        bean.title = "驾驶证";
                        bean.backGroundResourceId = R.drawable.jsz_4;
                        break;
                    case 14 :
                        bean.title = "行驶证";
                        bean.backGroundResourceId = R.drawable.xsz_5;
                        break;
                    case 20 :
                        bean.title = "其他照片";
                        break;
                    default:
                        bean = null;
                        showErrorTip("拍照类型有误");
                        break;
                }
            } catch (Exception e) {
              e.printStackTrace();
            }
            return bean;
         }

         @Override
         public void locationSuccess(BDLocation location) {
             if(location == null) {
                 return ;
             }
             try {
                 final JSONObject jsonObject = new JSONObject();
                 jsonObject.put("latitude", location.getLatitude());
                 jsonObject.put("longitude", location.getLongitude());
                 //定位成功
                 mWebView.post(new Runnable() {
                     @Override
                     public void run() {
                         mWebView.loadUrl("javascript:kckphnlocation('"+ jsonObject.toString() + "')");
                     }
                 });
             } catch (Exception e) {
                 e.printStackTrace();
             }
         }

         @Override
         public void locationFail() {
            showErrorTip("定位失败");
         }

         @Override
         public void showGpsDialog() {
             if(mDialog == null) {
                initDialog();
             }
             mDialog.show();
         }
     }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 99 && resultCode == HeNanSurfaceViewCameraActivity.RESULT_OK) {
            final String path = data.getStringExtra("image");
            if (TextUtils.isEmpty(path)) {
                showErrorTip("拍照图片有误，请重新拍照！");
                return;
            }

            //图片进行压缩上传
            String imageData = StringUtils.File2Base64(path);
            mPresenter.kckpUploadPhoto(imageData, mCurrentType);
        } else if(requestCode == SETTING_LOCATION_WEBVIEW ){
            //开始定位
            locationHelper.start();
        }
    }
}
